﻿/********************************************************************************/
// <copyright file="AdminController.cs" company="Asia E-Business Solutions">
//     Copyright © 2012. All right reserved
// </copyright>
// <history>
//     <change who="Phuoc Le" date="02/01/2013 4:23:17 PM">Created</change>
// </history>
/********************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Configuration;
using System.Web.Mvc;
using JLL.China.Application;
using JLL.China.Infrastructure.Services;
using JLL.China.Web.Areas.Portal.Models;
using JLL.China.Model;
using JLL.China.Web.Libraries;
namespace JLL.China.Web.Areas.Portal.Controllers
{
    public class AdminController : Controller
    {
        protected int defaultPageSize = Int32.Parse(WebConfigurationManager.AppSettings["page_size_default"]);
        //
        // GET: /Portal/Admin/

       // [CustomAuthorize(Roles = "International")]
        public ActionResult Index(int? page)
        {
           
            if (Session["page_size_default"] != null)
            {
                ViewData["per-page"] = Session["page_size_default"].ToString();
                defaultPageSize = Int32.Parse(Session["page_size_default"].ToString());
            }
            else
            {
                ViewData["per-page"] = defaultPageSize;
            }
            int currentPageIndex = page.HasValue ? page.Value : 1;
            //Strore Session
            Session["pageindex"] = currentPageIndex;
            var model = AdminService.GetAllAdmins().ToPagedList(currentPageIndex,defaultPageSize);
            return View(model);
        }

        //
        // GET: /Portal/Admin/Create

        public ActionResult Create()
        {
            var model = new AdminModel();
            model.Admin = new Admin();
            var modules = AdminService.FindAllModules();
            model.AllModules = new List<ModuleViewModel>();
            foreach (var module in modules)
            {
                var moduleview = new ModuleViewModel { ID = module.ID, Name = module.ModuleName, IsChecked = true };
                model.AllModules.Add(moduleview);
            }

            return View(model);
        } 

        //
        // POST: /Portal/Admin/Create

        [HttpPost]
        public ActionResult Create(AdminModel model)
        {
            Admin existAdmin = null;

            if (model.Admin.ID != Guid.Empty)
            {
                existAdmin = AdminService.GetAdmin(model.Admin.ID);
            }

            model.Admin.Modules = new List<Module>();

            foreach (var item in model.SelectedModules)
            {
               
                    var module = AdminService.FindModuleById(item);
                    module.Permission = "rw";
                    model.Admin.Modules.Add(module);
                
            }

            if (model.Admin.ID != Guid.Empty)
            {
                model.Admin.Group = existAdmin.Group;
                AdminService.UpdateAdmin(model.Admin);
            }
            else
            {
                model.Admin.ID = Guid.NewGuid();
                model.Admin.Group = new MemberGroup { ID = 1 };
                AdminService.CreateAdmin(model.Admin);
            }

            AdminService.CommitChanges();
            Session["message"] = "Update profile successfully.";
            Session["messageType"] = "Success";
            return RedirectToAction("Index");
        }
        
        //
        // GET: /Portal/Admin/Edit/5
 
        public ActionResult Edit(Guid id)
        {
            var model = new AdminModel();
            model.Admin = AdminService.GetAdmin(id);
            var modules = AdminService.FindAllModules();
            model.AllModules = new List<ModuleViewModel>();
            foreach (var module in modules)
            {
                var moduleview = new ModuleViewModel();
                if (model.Admin.Modules.FirstOrDefault(x => x.ID == module.ID) != null)
                {
                    moduleview.ID = module.ID; moduleview.Name = module.ModuleName; moduleview.IsChecked = true;
                }
                else
                {
                    moduleview.ID = module.ID; moduleview.Name = module.ModuleName; moduleview.IsChecked = false;
                }
                model.AllModules.Add(moduleview);
            }

            return View("Create",model);
        }

        //
        // GET: /Portal/Admin/Delete/5
 
        public ActionResult Delete(Guid id)
        {
            var model = new Admin { ID = id };
            AdminService.DeleteAdmin(model);
            AdminService.CommitChanges();
            return RedirectToAction("Index");
        }

        //
        // 
        public ActionResult ChangeStatus(Guid id)
        {
            var model = AdminService.GetAdmin(id);
            if (model.IsActive)
                model.IsActive = false;
            else
                model.IsActive = true;
            AdminService.UpdateAdmin(model);
            AdminService.CommitChanges();
            return RedirectToAction("Index");
        }

       

        ///GET: /Portal/Event/Selected?status=active
        public ActionResult SelectedUser(string status, IEnumerable<Guid> selected)
        {
            try
            {
                
                if (status.Equals("active"))
                {
                    foreach (var key in selected)
                    {
                        var model = AdminService.GetAdmin(key);
                        if (!model.IsActive)
                        {
                            model.IsActive = true;
                            AdminService.UpdateAdmin(model);
                            AdminService.CommitChanges();
                        }
                    }
                   
                }

                if (status.Equals("inactive"))
                {
                    foreach (var key in selected)
                    {
                        var model = AdminService.GetAdmin(key);
                        if (model.IsActive)
                        {
                            model.IsActive = false;
                            AdminService.UpdateAdmin(model);
                            AdminService.CommitChanges();
                        }
                    }
                    
                }

                if (status.Equals("remove"))
                {
                    foreach (var key in selected)
                    {
                        var model = new Admin { ID = key };
                        AdminService.DeleteAdmin(model);
                        AdminService.CommitChanges();
                    }
                }

                Session["message"] = "Records updated successfully.";
                Session["messageType"] = "Success";
            }
            catch (Exception)
            {
                Session["message"] = "Records updated unsuccessfully.";
                Session["messageType"] = "Error";
            }


            return RedirectToAction("Index");
            //  return RedirectToAction("Index");
        }



        // GET: /Portal/Profile?user = admin

        public ActionResult Profile(string id)
        {
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc != null)
            {
                var model = new AdminModel();
                model.Admin = AdminService.GetAdmin(id);
                //return RedirectToAction("Login", "Home", new { area = "" });
                return View(model);
            }
            else
            {
                return RedirectToAction("Login", "Home", new { area = "" });
            }
           
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Profile(AdminModel model)
        {
            try
            {
                //
                var user = AdminService.GetAdmin(model.Admin.ID);
                user.Password = model.Admin.Password;
                AdminService.UpdateAdmin(user);
                AdminService.CommitChanges();
                Session["message"] = "Update profile successfully.";
                Session["messageType"] = "Success";
            }
            catch (Exception)
            {
                
                throw;
            }
            
            return RedirectToAction("Index");
        }


    }
}
